//
//  schoolHomeViewController.m
//  ioschishan
//
//  Created by 千翼网络科技 on 2017/8/1.
//  Copyright © 2017年 qianyi. All rights reserved.
//

#import "schoolHomeViewController.h"
#import "HomeLookOverTeacherCell.h"
#import "bottomTableViewCell.h"
#import "schoolHomeTeacherTableViewCell.h"
#import "SDCycleScrollView.h"
#import "MJRefresh.h"

@interface schoolHomeViewController ()<UITableViewDelegate , UITableViewDataSource,SDCycleScrollViewDelegate>{
    
    NSArray *titleArray;
    NSArray *imgArray;
    
    int mark;//0教师 1众筹
    
    int teacherPage;
    int crowdPage;
    int mjMark;//1下拉刷新 2上拉加载
}

@property(nonatomic,strong) SDCycleScrollView *cycleScrollView;

@property(nonatomic,strong) UILabel *schoolNameLabel;
@property(nonatomic,strong) UILabel *locationLabel;
@property(nonatomic,strong) UILabel *messagelabel;

@property(nonatomic,strong) UIView *btnView;
@property(nonatomic,strong) UIView *btnRightView;

@property(nonatomic,strong) NSMutableArray *teacherDataArray;
@property(nonatomic,strong) NSMutableArray *crowdDataArray;
@property(nonatomic,strong) NSMutableArray *dataArray;
@property(nonatomic,strong) NSMutableDictionary *dataDic;
@property(nonatomic,strong) UITableView *helpTableView;

@end

@implementation schoolHomeViewController

- (void)viewWillAppear:(BOOL)animated{
    
    //下拉刷新
    _helpTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        mjMark = 1;
        teacherPage = 1;
        crowdPage = 1;
        
        if (mark == 0) {
            
            [self requestTeacherData];
            
        }else{
            
            [self requestCrowdData];
            
        }
        
        [_helpTableView.mj_header endRefreshing];
        
    }];
    
    //上拉加载
    _helpTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        mjMark = 2;
        
        if (mark == 0) {
            
            teacherPage ++;
            [self requestTeacherData];
            
        }else{
            
            crowdPage ++;
            [self requestCrowdData];
            
        }
        
        [_helpTableView.mj_footer endRefreshing];
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    [self requestSchoolData];
    [self requestTeacherData];
    [self requestCrowdData];
}

#pragma mark ----------------------- requestData ---------------------

- (void)requestSchoolData{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
    hud.tag = 500;
    //提示文本
    hud.labelText = @"正在加载...";
    //是否有遮罩
    hud.dimBackground = YES;
    
    NSMutableDictionary *productParams = [[NSMutableDictionary alloc]init];
    [productParams setValue: [PublicFunction getConfigWithKey:@"token"] forKey:@"token"];
    [productParams setValue: _idStr forKey:@"school_id"];
    
    [[MNetworkHandler sharedInstance]conURL:more_schoolData
                                networkType:NetWorkPOST
                                     params:productParams
                                   delegate:nil
                                    showHUD:NO
                               successBlock:^(id returnData) {
                                   
                                   if ([[returnData objectForKey:@"code"]intValue] == 1) {
                                       
                                       [hud removeFromSuperview];
                                       
                                       _dataDic = returnData[@"data"];
                                       NSLog(@"\n\n\n===学校主页===\n\n\n%@",_dataDic);
                                       [_helpTableView reloadData];
                                       
                                   }else{
                                       
                                       [hud removeFromSuperview];
                                       [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:1.0f];
                                   }
                                   
                               } failureBlock:^(NSError *error) {
                                   
                                   [hud removeFromSuperview];
                                   NSLog(@"%@",error);
                                   [PublicFunction showAlert:nil message:@"没有连接网络" duration:1.0f];
                               }];
}

- (void)requestTeacherData{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
    hud.tag = 500;
    //提示文本
    hud.labelText = @"正在加载...";
    //是否有遮罩
    hud.dimBackground = YES;
    
    NSMutableDictionary *productParams = [[NSMutableDictionary alloc]init];
    [productParams setValue: [PublicFunction getConfigWithKey:@"token"] forKey:@"token"];
    [productParams setValue: _idStr forKey:@"school_id"];
    [productParams setValue: [NSString stringWithFormat:@"%d",teacherPage] forKey:@"page"];
    
    [[MNetworkHandler sharedInstance]conURL:more_schoolDataTeacher
                                networkType:NetWorkPOST
                                     params:productParams
                                   delegate:nil
                                    showHUD:NO
                               successBlock:^(id returnData) {
                                   
                                   if ([[returnData objectForKey:@"code"]intValue] == 1) {
                                       
                                       [hud removeFromSuperview];
                                       
                                       if (mjMark == 1) {
                                           
                                           _teacherDataArray = returnData[@"data"];
                                           
                                       }else{
                                           
                                           [_teacherDataArray addObjectsFromArray:returnData[@"data"]];
                                           
                                       }
                                       NSLog(@"\n\n\n===学校主页-老师===\n\n\n%@",_teacherDataArray);
                                       [_helpTableView reloadData];
                                       
                                   }else{
                                       
                                       [hud removeFromSuperview];
                                       [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:1.0f];
                                   }
                                   
                               } failureBlock:^(NSError *error) {
                                   
                                   [hud removeFromSuperview];
                                   NSLog(@"%@",error);
                                   [PublicFunction showAlert:nil message:@"没有连接网络" duration:1.0f];
                               }];
}

- (void)requestCrowdData{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
    hud.tag = 500;
    //提示文本
    hud.labelText = @"正在加载...";
    //是否有遮罩
    hud.dimBackground = YES;
    
    NSMutableDictionary *productParams = [[NSMutableDictionary alloc]init];
    [productParams setValue: [PublicFunction getConfigWithKey:@"token"] forKey:@"token"];
    [productParams setValue: _idStr forKey:@"school_id"];
    [productParams setValue: [NSString stringWithFormat:@"%d",crowdPage] forKey:@"page"];
    
    [[MNetworkHandler sharedInstance]conURL:more_schoolDataCrowd
                                networkType:NetWorkPOST
                                     params:productParams
                                   delegate:nil
                                    showHUD:NO
                               successBlock:^(id returnData) {
                                   
                                   if ([[returnData objectForKey:@"code"]intValue] == 1) {
                                       
                                       [hud removeFromSuperview];
                                       
                                       if (mjMark == 1) {
                                           
                                           _crowdDataArray = returnData[@"data"];
                                           
                                       }else{
                                           
                                           [_crowdDataArray addObjectsFromArray:returnData[@"data"]];
                                           
                                       }
                                       NSLog(@"\n\n\n===学校主页-众筹===\n\n\n%@",_crowdDataArray);
                                       [_helpTableView reloadData];
                                       
                                   }else{
                                       
                                       [hud removeFromSuperview];
                                       [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:1.0f];
                                   }
                                   
                               } failureBlock:^(NSError *error) {
                                   
                                   [hud removeFromSuperview];
                                   NSLog(@"%@",error);
                                   [PublicFunction showAlert:nil message:@"没有连接网络" duration:1.0f];
                               }];
}

#pragma mark ------------------ init -------------------

- (void)initView{
    
    self.title = @"学校主页";
    
    _dataArray = [[NSMutableArray alloc]init];
    mjMark = 1;
    teacherPage = 1;
    crowdPage = 1;
    
    _helpTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, scrWidth(), scrHeight() - 64 - screenScale(49))];
    _helpTableView.backgroundColor = getColor(@"ffffff");
    _helpTableView.delegate = self;
    _helpTableView.dataSource = self;
    _helpTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_helpTableView];
    
    UIView *threadView = [[UIView alloc]initWithFrame:CGRectMake(0, screenScale(1), scrWidth(), screenScale(0.7))];
    threadView.backgroundColor = getColor(@"cccccc");
    [self.view addSubview:threadView];
    
    UIButton *finishBtn = [ConfigXp buttonWithFrame:CGRectZero
                                              title:@"绑定该学校"
                                         titleColor:getColor(@"ffffff")
                                               font:get4sFont(13)
                                    backgroundColor:getColor(@"3a95ff")
                                              image:nil];
    finishBtn.layer.cornerRadius = screenScale(3);
    [finishBtn addTarget:self action:@selector(finishBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:finishBtn];
    [finishBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view).with.offset(0);
        make.left.mas_equalTo(self.view).with.offset(0);
        make.right.mas_equalTo(self.view).with.offset(0);
        make.height.mas_equalTo(screenScale(49));
    }];
}

#pragma mark -------------------- click ----------------------

- (void)leftBtnClick{
    
    mark = 0;
    [_helpTableView reloadData];
}

- (void)rightBtnClick{
    
    mark = 1;
    [_helpTableView reloadData];
}

- (void)finishBtnClick{
    
    NSDictionary *dict =[[NSDictionary alloc]initWithObjectsAndKeys:@"yes",@"school",_schoolNameLabel.text,@"what",_dataDic[@"school_pic"][0][@"school_id"],@"schoolId", nil];
    NSNotification *notification =[NSNotification notificationWithName:@"school" object:nil userInfo:dict];
    [[NSNotificationCenter defaultCenter] postNotification:notification];

    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:2] animated:YES];
}

#pragma mark -------------------- tableView ----------------------

#pragma mark --- UITableViewDelegate ---

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 1) {
        
        return screenScale(44);
    }
    
    return screenScale(281 + 88 + 8);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        return 0;
        
    }else{
        
        if (mark == 0) {
            
            return 70;
        }
        
        return screenScale(190);
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            
//            walletViewController *vc = [[walletViewController alloc]init];
//            vc.hidesBottomBarWhenPushed = YES;
//            [self.navigationController pushViewController:vc animated:YES];
            
        }else if (indexPath.row == 1){
            
//            helpViewController *vc = [[helpViewController alloc]init];
//            vc.hidesBottomBarWhenPushed = YES;
//            [self.navigationController pushViewController:vc animated:YES];
            
        }else if (indexPath.row == 2){
            
//            teacherViewController *vc = [[teacherViewController alloc]init];
//            vc.hidesBottomBarWhenPushed = YES;
//            [self.navigationController pushViewController:vc animated:YES];
            
        }else if (indexPath.row == 3){
            
//            setupViewController *vc = [[setupViewController alloc]init];
//            vc.hidesBottomBarWhenPushed = YES;
//            [self.navigationController pushViewController:vc animated:YES];
            
        }
    }
    
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section == 1) {
        
        UIView *bottomHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, scrWidth(), screenScale(44))];
        bottomHeaderView.backgroundColor = getColor(@"ffffff");
        
        ///
        
        UIButton *leftBtn = [ConfigXp buttonWithFrame:CGRectZero
                                                title:@"老师"
                                           titleColor:getColor(@"333333")
                                                 font:get4sFont(13)
                                      backgroundColor:nil
                                                image:nil];
        [leftBtn addTarget:self action:@selector(leftBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [bottomHeaderView addSubview:leftBtn];
        [leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(bottomHeaderView).with.offset(0);
            make.left.mas_equalTo(bottomHeaderView).with.offset(screenScale(109));
            
            make.height.mas_equalTo(screenScale(44));
        }];
        
        _btnView = [[UIView alloc]init];
        _btnView.backgroundColor = getColor(@"D80A09");
        [bottomHeaderView addSubview:_btnView];
        [_btnView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(bottomHeaderView).with.offset(screenScale(36));
            make.left.mas_equalTo(bottomHeaderView).with.offset(screenScale(112));
            make.width.mas_equalTo(screenScale(24));
            make.height.mas_equalTo(screenScale(2));
        }];
        
        ///
        
        UIButton *rightBtn = [ConfigXp buttonWithFrame:CGRectZero
                                                 title:@"众筹"
                                            titleColor:getColor(@"333333")
                                                  font:get4sFont(13)
                                       backgroundColor:nil
                                                 image:nil];
        [rightBtn addTarget:self action:@selector(rightBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [bottomHeaderView addSubview:rightBtn];
        [rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(bottomHeaderView).with.offset(0);
            make.left.mas_equalTo(bottomHeaderView).with.offset(screenScale(233));
            
            make.height.mas_equalTo(screenScale(44));
        }];
        
        _btnRightView = [[UIView alloc]init];
        _btnRightView.backgroundColor = getColor(@"D80A09");
        [bottomHeaderView addSubview:_btnRightView];
        [_btnRightView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(bottomHeaderView).with.offset(screenScale(36));
            make.left.mas_equalTo(bottomHeaderView).with.offset(screenScale(236));
            make.width.mas_equalTo(screenScale(24));
            make.height.mas_equalTo(screenScale(2));
        }];
        
        ///
        
        UIView *threadView = [[UIView alloc]init];
        threadView.backgroundColor = getThreadColor();
        [bottomHeaderView addSubview:threadView];
        [threadView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(bottomHeaderView.mas_bottom).with.offset(0);
            make.left.mas_equalTo(bottomHeaderView).with.offset(0);
            make.right.mas_equalTo(bottomHeaderView).with.offset(0);
            make.height.mas_equalTo(screenScale(0.5));
        }];
        
        ///
        
        if (mark == 0) {
            
            _btnView.hidden = NO;
            _btnRightView.hidden = YES;
            
        }else{
            
            _btnView.hidden = YES;
            _btnRightView.hidden = NO;
        }
        
        return bottomHeaderView;
    }
    
    //////////////////////
    
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, scrWidth(), screenScale(253))];
    headerView.backgroundColor = getColor(@"ffffff");
    
    ///
    
    NSArray *arrMu = @[@"3479.jpg_wh1200",@"3479.jpg_wh1200",@"3479.jpg_wh1200",@"3479.jpg_wh1200"];
    self.cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, scrWidth(), screenScale(281)) imageNamesGroup:arrMu];
    self.cycleScrollView.backgroundColor = [UIColor whiteColor];
    self.cycleScrollView.autoScroll = YES;
    self.cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    self.cycleScrollView.delegate = self;
    self.cycleScrollView.pageDotColor = [UIColor grayColor]; // 自定义分页控件小圆标颜色
    self.cycleScrollView.currentPageDotImage = [UIImage imageNamed:@"椭圆-3-拷贝-2"];
    self.cycleScrollView.pageDotImage = [UIImage imageNamed:@"椭圆-3-拷贝-3"];
    self.cycleScrollView.placeholderImage = [UIImage imageNamed:@"XQ1"];
    [headerView addSubview:self.cycleScrollView];
    
    _schoolNameLabel = [ConfigXp labelWithFrame:CGRectZero
                                           text:@"光明小学"
                                      textColor:getColor(@"4a4a4a")
                                           font:get4sFont(12)
                                  textAlignment:NSTextAlignmentLeft
                                backgroundColor:[UIColor clearColor]];
    [headerView addSubview:_schoolNameLabel];
    [_schoolNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(headerView).with.offset(screenScale(297));
        make.left.mas_equalTo(headerView).with.offset(screenScale(15));
        make.right.mas_equalTo(headerView).with.offset(screenScale(-45));
        
    }];
    
    _locationLabel = [ConfigXp labelWithFrame:CGRectZero
                                           text:@"沈阳"
                                      textColor:getColor(@"9b9b9b")
                                           font:get4sFont(11)
                                  textAlignment:NSTextAlignmentLeft
                                backgroundColor:[UIColor clearColor]];
    [headerView addSubview:_locationLabel];
    [_locationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(headerView).with.offset(screenScale(298));
        make.right.mas_equalTo(headerView).with.offset(screenScale(-15));
        
        
    }];
    
    _messagelabel = [ConfigXp labelWithFrame:CGRectZero
                                           text:@"介绍一下你的学校吧～"
                                      textColor:getColor(@"9b9b9b")
                                           font:get4sFont(11)
                                  textAlignment:NSTextAlignmentLeft
                                backgroundColor:[UIColor clearColor]];
    _messagelabel.numberOfLines = 2;
    [headerView addSubview:_messagelabel];
    [_messagelabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(headerView).with.offset(screenScale(321));
        make.left.mas_equalTo(headerView).with.offset(screenScale(15));
        make.right.mas_equalTo(headerView).with.offset(screenScale(-15));
        
    }];
    
    UIView *threadView = [[UIView alloc]initWithFrame:CGRectMake(0, screenScale(370), scrWidth(), screenScale(8))];
    threadView.backgroundColor = getColor(@"f5f5f5");
    [headerView addSubview:threadView];
    
    ///
    
    NSMutableArray *myarr = [[NSMutableArray alloc]init];
    for (int i = 0; i < [_dataDic[@"school_pic"] count]; i++) {
        
        NSString *urlN = manage(AP_HOST, _dataDic[@"school_pic"][i][@"path"]);
        
        [myarr addObject:urlN];
    }
    [self.cycleScrollView setLocalizationImageNamesGroup:myarr];
    [self.cycleScrollView reloadInputViews];
    
    _schoolNameLabel.text = _dataDic[@"name"];
    _locationLabel.text = _dataDic[@"address"];
    _messagelabel.text = _dataDic[@"content"];
    
    ///
    
    return headerView;
}

#pragma mark --- UITableViewDataSource ---

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0) {
        
        return 0;
        
    }else{
        
        if (mark == 0) {
            
            return [_teacherDataArray count];
            
        }else{
            
            return [_crowdDataArray count];
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 1) {
        
        if (mark == 0) {
            
            [tableView registerClass:[schoolHomeTeacherTableViewCell class] forCellReuseIdentifier:@"schoolHomeTeacherTableViewCell"];
            schoolHomeTeacherTableViewCell *cell = (schoolHomeTeacherTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"schoolHomeTeacherTableViewCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            cell.index = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
            cell.teacherId = _teacherDataArray[indexPath.row][@"member_id"];
            
            NSString *urlN = manage(AP_HOST, _teacherDataArray[indexPath.row][@"header_img"]);
            NSURL *urlW = [NSURL URLWithString:urlN];
            [cell.leftImg sd_setImageWithURL:urlW placeholderImage:[UIImage imageNamed:@"niunai"]];
            cell.nameLable.text = _teacherDataArray[indexPath.row][@"user_name"];
            cell.statusLable.text = _teacherDataArray[indexPath.row][@"content"];
            
            return cell;
        }
        
        [tableView registerClass:[bottomTableViewCell class] forCellReuseIdentifier:@"bottomTableViewCell"];
        bottomTableViewCell *cell = (bottomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"bottomTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        NSString *urlN = manage(AP_HOST, _crowdDataArray[indexPath.row][@"pic"]);
        NSURL *urlW = [NSURL URLWithString:urlN];
        [cell.leftImg sd_setImageWithURL:urlW placeholderImage:[UIImage imageNamed:@"niunai"]];
        
        cell.nameLable.text = _crowdDataArray[indexPath.row][@"title"];
        
        cell.textLable.text = _crowdDataArray[indexPath.row][@"content"];
        
        [cell.progressView setProgress:[_crowdDataArray[indexPath.row][@"money"] floatValue] / [_crowdDataArray[indexPath.row][@"target"] floatValue] animated:YES];
        
        cell.progressLable.text = [NSString stringWithFormat:@"%.0f",[_crowdDataArray[indexPath.row][@"money"] floatValue] / [_crowdDataArray[indexPath.row][@"target"] floatValue]];
        
        NSString *urlN1 = manage(AP_HOST, _crowdDataArray[indexPath.row][@"header_img"]);
        NSURL *urlW1 = [NSURL URLWithString:urlN1];
        [cell.headImg sd_setImageWithURL:urlW1 placeholderImage:[UIImage imageNamed:@"niunai"]];
        
        cell.personLable.text = _crowdDataArray[indexPath.row][@"user_name"];
        
        cell.moneyLable.text = _crowdDataArray[indexPath.row][@"target"];
        
        cell.peopleLable.text = _crowdDataArray[indexPath.row][@"support"];
        
        cell.dayLable.text = _crowdDataArray[indexPath.row][@"days"];
        
        return cell;
    }
    
    [tableView registerClass:[bottomTableViewCell class] forCellReuseIdentifier:@"bottomTableViewCell"];
    bottomTableViewCell *cell = (bottomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"bottomTableViewCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

@end
